/*
 
Copyright Eric C. McCreath 2012  <ericm@cs.anu.edu.au>

This file is part of the clapper-webcam-recorder project.

clapper-webcam-recorder is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.

clapper-webcam-recorder is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with clapper-webcam-recorder.  If not, see <http://www.gnu.org/licenses/>.

 */



#include<stdio.h>


#include <GL/glut.h>
#include <GL/glu.h>
#include <linux/videodev2.h>
#include"quickview.h"
#include"display.h"
#include"webcam.h"

int endprogram = 0;

static void updateTexture(const unsigned char *p)
{
    int x,y;
    for (y = 0; y < ydim; y++) {    
        for (x = 0; x < xdim; x += 2) { 
            setcolortexbuf(x,y,p[x*2 + y*640*2], 
                               p[x*2 + 1 + y*640*2], 
                               p[x*2 + 3 + y*640*2]);
            setcolortexbuf(x+1,y,p[(x+1)*2 + y*640*2],
                                 p[(x+1)*2 - 1 + y*640*2],
                                 p[(x+1)*2 + 1 + y*640*2]); 
        }
    }    
}


void keypress (unsigned char key, int x, int y) {
   printf("key press\n");
   endprogram = 1;
  
}


void display(void) {
    drawtexture();
    glFlush(); 
    glutSwapBuffers();

}

void endProgram() {
    stop_webcam();
    close_webcam();
    exit(0);
}

void timer() {
    struct v4l2_buffer buf;

    getbuffer_webcam(&buf);
    updateTexture(buffers[buf.index].start);
    releasebuffer_webcam(&buf);

    glutPostRedisplay();
    if (endprogram) {
        endProgram();
    } else {
        glutTimerFunc(1,timer,0);
    } 
}



int main(int argc, char **argv) {
   open_webcam("/dev/video0");
   init_webcam();
   start_webcam();
   glutInit(&argc, argv);
   setupdisplay(xdim,ydim);
   glutDisplayFunc(display);
   glutTimerFunc(25,timer,0);
   glutKeyboardFunc(keypress);
   
   glutMainLoop();  // this never returns !!
   return 0;
}
